﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
using OneMake.DataAccess;
using OneMake.Model;
using Tools.ExportToExcel;

namespace OneMake.Winforms
{
    public partial class StatisticsControl : UserControl
    {
        private DataHelper dataHelper = new DataHelper();

        private string selTableName = "";       //当前选择树节点
        private int selShopId = 0;              //当前店铺
        private DateTime selBeginTime;          //开始时间
        private DateTime selEndTime;            //结束时间
        private int selPage = 1;                //第几页
        private readonly int itemsPerPage = 50;    //每页几条
        private long totalPage = 1;


        public StatisticsControl()
        {
            InitializeComponent();
        }

        private void StatisticsControl_Load(object sender, EventArgs e)
        {
            dtpBegin.Value = DateTime.Now.AddDays(-90);
            dtpEnd.Value = DateTime.Now;

            LoadShops();

            if (cbShops.SelectedValue != null)
                selShopId = System.Convert.ToInt32(cbShops.SelectedValue.ToString());
            else
                selShopId = 0;

            selBeginTime = dtpBegin.Value;
            selEndTime = dtpEnd.Value;
            selPage = 1;
        }

        private void LoadShops()
        {
            cbShops.DataSource = dataHelper.GetShops();
            cbShops.DisplayMember = "name";
            cbShops.ValueMember = "shopid";
            if (cbShops.Items.Count > 0)
                cbShops.SelectedIndex = 0;
        }

        //选中树状节点
        public void UpdateView(string tableName)
        {
            selTableName = tableName;
            selShopId = _getShopID();
            selBeginTime = dtpBegin.Value;
            selEndTime = dtpEnd.Value;
            selPage = 1;

            Dictionary<string, string> attrMap = dataHelper.GetTableFieldMap(tableName);
            
            dgvReport.Columns.Clear();
            foreach (KeyValuePair<string, string> item in attrMap)
            {
                DataGridViewColumn col = new DataGridViewTextBoxColumn();
                col.Name = item.Key;
                col.HeaderText = item.Value;
                col.DataPropertyName = item.Key;
                dgvReport.Columns.Add(col);
            }

            UpdateView();
        }

        private void UpdateView()
        {
            if (selTableName == "")
                return;

            switch (selTableName)
            {
                case "ct_d_jxdb":
                    _updateView<ct_d_jxdb>("stat_datetime,ww");
                    break;
                case "ct_d_cgldb":
                    _updateView<ct_d_cgldb>("stat_datetime,ww");
                    break;
                case "ct_d_gzldb":
                    _updateView<ct_d_gzldb>("stat_datetime,ww");
                    break;
                case "ct_d_kdjdb":
                    _updateView<ct_d_kdjdb>("stat_datetime,ww");
                    break;
                case "ct_d_kjsdb":
                    _updateView<ct_d_kjsdb>("stat_datetime,ww");
                    break;
                case "ct_d_tkqkdb":
                    _updateView<ct_d_tkqkdb>("stat_datetime,ww");
                    break;
                case "ct_d_comment":
                    _updateView<ct_d_comment>("stat_datetime,ww");
                    break;
                case "ct_d_order":
                    _updateView<ct_d_order>("stat_datetime,ww");
                    break;
                case "ct_d_quire":
                    _updateView<ct_d_quire>("stat_datetime,ww");
                    break;
                case "ct_d_kfghzb":
                    _updateView<ct_d_kfghzb>("stat_datetime,ww");
                    break;
                case "hdp_d_return":
                    _updateView<hdp_d_return>("stat_datetime");
                    break;
                case "hdp_d_stat":
                    _updateView<hdp_d_stat>("stat_datetime");
                    break;
                case "hdp_d_deal":
                    _updateView<hdp_d_deal>("stat_datetime,deal_createtime");
                    break;
                case "hdp_d_vdepth":
                    _updateView<hdp_d_vdepth>("stat_datetime");
                    break;
                case "htjy_d_orders":
                    _updateView<htjy_d_orders>("stat_datetime");
                    break;
                case "htjy_d_products":
                    _updateView<htjy_d_products>("stat_datetime");
                    break;
                case "htjy_d_refund":
                    _updateView<htjy_d_refund>("stat_datetime");
                    break;
                case "jhs_d_pq":
                    _updateView<jhs_d_pq>("stat_datetime,brand,category");
                    break;
                case "jhs_d_yxhd":
                    _updateView<jhs_d_yxhd>("stat_datetime,shopname");
                    break;
                case "lz_d_ztcjb":
                    _updateView<lz_d_ztcjb>("stat_datetime");
                    break;
                case "lz_d_area":
                    _updateView<lz_d_area>("stat_datetime");
                    break;
                case "lz_d_bdetail":
                    _updateView<lz_d_bdetail>("stat_datetime");
                    break;
                case "lz_d_flowsource":
                    _updateView<lz_d_flowsource>("stat_datetime,source");
                    break;
                case "lz_d_homepage":
                    _updateView<lz_d_homepage>("stat_datetime");
                    break;
                case "lz_d_hpdetail":
                    _updateView<lz_d_hpdetail>("stat_datetime");
                    break;
                case "lz_d_innkeywords":
                    _updateView<lz_d_innkeywords>("stat_datetime,keyword");
                    break;
                case "lz_d_innervisit":
                    _updateView<lz_d_innervisit>("stat_datetime");
                    break;
                case "lz_d_outkeyword":
                    _updateView<lz_d_outkeyword>("stat_datetime");
                    break;
                case "lz_d_prdsale":
                    _updateView<lz_d_prdsale>("stat_datetime");
                    break;
                case "lz_d_prdvisit":
                    _updateView<lz_d_prdvisit>("stat_datetime");
                    break;
                case "lz_d_prometion":
                    _updateView<lz_d_prometion>("stat_datetime");
                    break;
                case "lz_d_shopop":
                    _updateView<lz_d_shopop>("stat_datetime,stat_hour");
                    break;
                case "lz_m_shopop":
                    _updateView<lz_m_shopop>("stat_datetime,stat_hour");
                    break;
                case "lz_d_timestrips":
                    _updateView<lz_d_timestrips>("stat_datetime");
                    break;
                case "lz_w_acounts":
                    _updateView<lz_w_acounts>("stat_datetime");
                    break;
                case "lz_w_keywords":
                    _updateView<lz_w_keywords>("stat_datetime");
                    break;
                case "lz_w_prometion":
                    _updateView<lz_w_prometion>("stat_datetime");
                    break;
                case "lz_d_szid":
                    _updateView<lz_d_szid>("stat_datetime");
                    break;
                case "mf_m_gjccj":
                    _updateView<mf_m_gjccj>("stat_datetime,brand");
                    break;
                case "mf_m_gmpc":
                    _updateView<mf_m_gmpc>("stat_datetime,brand");
                    break;
                case "mf_m_gmsd":
                    _updateView<mf_m_gmsd>("stat_datetime,brand");
                    break;
                case "mf_m_kdj":
                    _updateView<mf_m_kdj>("stat_datetime,brand");
                    break;
                case "mf_m_lfsd":
                    _updateView<mf_m_lfsd>("stat_datetime,brand");
                    break;
                case "mf_m_mjdyfx":
                    _updateView<mf_m_mjdyfx>("stat_datetime,brand");
                    break;
                case "mf_m_qwatydf":
                    _updateView<mf_m_qwatydf>("stat_datetime");
                    break;
                case "mf_m_rmss":
                    _updateView<mf_m_rmss>("stat_datetime,brand");
                    break;
                case "mf_m_rspp":
                    _updateView<mf_m_rspp>("stat_datetime,category");
                    break;
                case "mf_m_spbj":
                    _updateView<mf_m_spbj>("stat_datetime,brand");
                    break;
                case "mf_m_tz":
                    _updateView<mf_m_tz>("stat_datetime,category");
                    break;
                case "mf_m_xbnl":
                    _updateView<mf_m_xbnl>("stat_datetime,brand");
                    break;
                case "ppf_d_antastore":
                    _updateView<ppf_d_antastore>("stat_datetime");
                    break;
                case "ppf_d_joeone_sales":
                    _updateView<ppf_d_joeone_sales>("stat_datetime");
                    break;
                case "ppf_d_joeone_store":
                    _updateView<ppf_d_joeone_store>("stat_datetime,prd_name");
                    break;
                case "product_archive":
                    _updateView<product_archive>("stat_datetime");
                    break;
                case "ppf_d_qipai_ess":
                    _updateView<ppf_d_qipai_ess>("stat_datetime");
                    break;
                case "ppf_d_qipai_store":
                    _updateView<ppf_d_qipai_store>("stat_datetime");
                    break;
                case "sh_d_thh":
                    _updateView<sh_d_thh>("stat_datetime");
                    break;
                case "xy_d_buyarea":
                    _updateView<xy_d_buyarea>("stat_datetime");
                    break;
                case "xy_d_visitarea":
                    _updateView<xy_d_visitarea>("stat_datetime");
                    break;
                case "mf_m_mjgmfx":
                    _updateView<mf_m_mjgmfx>("stat_datetime,category");
                    break;
                case "mf_m_ppsczdhq":
                    _updateView<mf_m_ppsczdhq>("stat_datetime,brand");
                    break;
                case "mf_m_qwsczdhq":
                    _updateView<mf_m_qwsczdhq>("stat_datetime,brand");
                    break;
                case "mf_m_rxppph":
                    _updateView<mf_m_rxppph>("stat_datetime,category");
                    break;
                default:
                    //default时候要怎么办?
                    MessageBox.Show("没找到view:" + selTableName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
        }

        private void _updateView<T>(string SortFields)
        {
            PetaPoco.Page<T> pages = dataHelper.GetReports<T>(selShopId, selBeginTime, selEndTime, selPage, itemsPerPage, SortFields);

            totalPage = pages.TotalPages;
            int currentPage = pages.TotalItems > 0 ? selPage : 0;
            lblTotal.Text = string.Format("第{0}页，共{1}页", currentPage, pages.TotalPages);

            dgvReport.DataSource = pages.Items;
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            btnPrint.Text = "请稍候...";
            btnPrint.Enabled = false;
            Tools.ExportToExcel.ExportToExcel exp = new Tools.ExportToExcel.ExportToExcel();
            sfdExportToxcel.FileName = "导出文件1.xlsx";
            sfdExportToxcel.Filter = "Excel表格(*.xlsx)|*.xlsx|全部文件(*.*)|*.*";
            sfdExportToxcel.FilterIndex = 1;
            sfdExportToxcel.RestoreDirectory = true;

            if (sfdExportToxcel.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfdExportToxcel.FileName;
                try
                {
                    exp.dataGridView2Excel(this.dgvReport, path);
                    MessageBox.Show("导出完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }

            btnPrint.Text = "导出";
            btnPrint.Enabled = true;
        }



        private void cbShops_SelectedIndexChanged(object sender, EventArgs e)
        {
            selShopId = _getShopID();
            selPage = 1;
            UpdateView();
        }

        private int _getShopID()
        {
            try
            {
                if (cbShops.SelectedValue != null)
                    return System.Convert.ToInt32(cbShops.SelectedValue.ToString());
                else
                    return 0;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Print(ex.Message);
            }
            return 0;
        }  
   
        private void dgvReport_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            //格式化日期, 假设名字为stat_datetime为显示日期的列
            if (dgvReport.Columns[e.ColumnIndex].HeaderText == "统计日期")
            {
                e.Value = string.Format("{0:yyyy-MM-dd}", Convert.ToDateTime(e.Value));
            }
            else if (dgvReport.Columns[e.ColumnIndex].HeaderText == "统计月份")
            {
                e.Value = string.Format("{0:yyyy-MM}", Convert.ToDateTime(e.Value));
            }
        }

        private void dtpBegin_ValueChanged(object sender, EventArgs e)
        {
            selBeginTime = dtpBegin.Value;
            selPage = 1;
            UpdateView();
        }

        private void dtpEnd_ValueChanged(object sender, EventArgs e)
        {
            selEndTime = dtpEnd.Value;
            selPage = 1;
            UpdateView();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (selPage > 1)
            {
                selPage--;
                UpdateView();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (selPage < totalPage)
            {
                selPage++;
                UpdateView();
            }
        }



        private void btnExpAll_Click(object sender, EventArgs e)
        {
            btnExpAll.Text = "请稍候...";
            btnExpAll.Enabled = false;

            Tools.ExportToExcel.ExportToExcel exp = new Tools.ExportToExcel.ExportToExcel();
            sfdExportToxcel.FileName = "导出文件1.xls";
            sfdExportToxcel.Filter = "Excel表格(*.xls)|*.xls|全部文件(*.*)|*.*";
            sfdExportToxcel.FilterIndex = 1;
            sfdExportToxcel.RestoreDirectory = true;

            if (sfdExportToxcel.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfdExportToxcel.FileName;
                try
                {
                    string bt = string.Format("{0:yyyy-MM-dd}", selBeginTime) + " 00:00:00";
                    string et = string.Format("{0:yyyy-MM-dd}", selEndTime) + " 23:59:59";
                    string sql = string.Format("SELECT * FROM {0} WHERE shopid={1} AND stat_datetime>='{2}' AND stat_datetime<='{3}' ORDER BY stat_datetime", selTableName, selShopId, bt, et);

                    using (var db = new PetaPoco.Database("mysql" + UserSession.Network))
                    {
                        DataTable table = db.ExecuteTable(sql);
                        Dictionary<string, string> attrMap = dataHelper.GetTableFieldMap(selTableName);
                        foreach (KeyValuePair<string, string> item in attrMap)
                        {
                            table.Columns[item.Key].ColumnName = item.Value;
                        }

                        exp.DataTabletoExcel(table, path);
                    }

                    MessageBox.Show("导出完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }

            btnExpAll.Text = "全部导出";
            btnExpAll.Enabled = true;
        }
    }
}
